// pages/dingdan/dingdan.js
Page({

  data: {
    time: '选择时间',
    timeText: '',
    showPicker: true,
    value: '',
    message: '',
    bzxx: false,
    isSelfTake: true,
    price: '',
    isxuanz:true,
    phone: "",
    phoneError: "",
    bzxx: false,
    bzmessage: "", 
    mymessage: null,
    isDiningDisabled: false,
    orderData: [],
    orderId:'',
    isNavigating: false,
  },

  onSubmit() {
    const { time, phone, isxuanz, mymessage ,isSelfTake,orderId } = this.data;

    if (!time || time === "选择时间") {
      wx.showToast({
        title: "请选择预约时间",
        icon: "none",
      });
      return;
    }
 
    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!phone || !phoneRegex.test(phone)) {
      wx.showToast({
        title: "请输入正确的手机号",
        icon: "none",
      });
      return;
    }

    const qucan = isSelfTake ? "自取" : "外卖";
    // 校验是否选择了就餐方式
    const diningType = isxuanz ? "店内就餐" : "打包外带";
  
    const orderNumber = Math.floor(1000 + Math.random() * 9000);
    // 订单数据
    const orderData = {
      time,
      phone,
      qucan,
      diningType,
      orderId,
      message: mymessage || "无备注", 
      orderNumber: orderNumber.toString() 
    };
  
    console.log("提交订单:", orderData);
  
    // 提交订单成功提示
    wx.showToast({
      title: "订单支付成功",
      icon: "success",
      duration: 1000, // 显示 2 秒后跳转
      success: () => {
        setTimeout(() => {
          wx.navigateBack(); // 返回上一页
        }, 2000);
      }
    });
    
    
    const db = wx.cloud.database();
    const usersCollection = db.collection('orders'); 

    usersCollection.where({
      orderId: orderId
    }).get().then(res=>{
      console.log("orderId",res);
      if (res.data && res.data.length > 0) {
        // 获取到文档的 _id
        const documentId = res.data[0]._id;
    
        // 更新数据
        usersCollection.doc(documentId).update({
          // data: orderData, // 要更新的数据
          data: {
            ...orderData, // 订单信息
            orderStatus: "已付款" // 修改支付状态
          },
          success: (updateRes) => {
            console.log("更新成功:", updateRes);
          },
          fail: (err) => {
            console.error("更新失败:", err);
          }
        });
      } else {
        console.log("未找到匹配的 orderId");
      }
    }).catch(error => {
      console.error("查询失败:", error);
    });


    
  },
  
  validatePhone(event) {
    const phone = event.detail.value;
    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!phoneRegex.test(phone)) {
      this.setData({
        phoneError: "请输入正确的手机号"
      });
    } else {
      this.setData({
        phoneError: ""
      });
    }
  }, 

 
  xuanze1() {
    if (this.data.isDiningDisabled) return; 
    this.setData({ isxuanz: true });
  },
  xuanze2(){
    this.setData({ isxuanz: false });
    
  },
  toggleSelfTake() {
    this.setData({ 
      isSelfTake: true, 
      isxuanz: true, // 自取默认选择店内就餐
      isDiningDisabled: false // 允许选择“店内就餐”
    });
  },
  
  toggleDelivery() {
    this.setData({ 
      isSelfTake: false, 
      isxuanz: false, // 外卖默认选择“打包外带”
      isDiningDisabled: true // 禁用“店内就餐”
    });
  },
  
  onTimeChange(e) {
    const selectedTime = e.detail.value;
    this.setData({
      time: selectedTime,
      showPicker: true,
    });
  },

  onPhoneInput(event) {
    this.setData({
      phone: event.detail.value
    });
  },

  // 手机号验证
  validatePhone(event) {
    const phone = event.detail.value;
    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!phoneRegex.test(phone)) {
      this.setData({
        phoneError: "请输入正确的手机号"
      });
    } else {
      this.setData({
        phoneError: ""
      });
    }
  },

  onChange(event) {
    let inputText = event.detail.value;
  
    // 限制字数最多 30 个
    if (inputText.length > 30) {
      inputText = inputText.substring(0, 30);
    }
  
    this.setData({
      bzmessage: inputText
    });
  },
  

  kzxx() {
    this.setData({
      bzxx: true,
      bzmessage: this.data.mymessage === "口味、偏好等要求" ? "" : (this.data.mymessage || "")
    });
  },
  
  kzxxf() {
    this.setData({
      bzxx: false,
    });
  },

  lyqd() {
    const bzmessage = this.data.bzmessage || "";
    this.setData({
      mymessage: bzmessage.trim() || "口味、偏好等要求",
      bzxx: false
    });
  },
  
  

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const app = getApp();
    const orderData = app.globalData.orderData;
  
    if (orderData) {
      this.setData({
        orderId: orderData.orderId,
        orderData: orderData
      });
    } else {
      wx.showToast({
        title: "订单数据未找到",
        icon: "none"
      });
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const app = getApp();
    this.setData({
      orderData: app.globalData.orderData || [],
      orderId:app.globalData.orderData.orderId,
      price: (app.globalData.orderData?.totalPrice || 0) * 100 
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})